package com.sjd.mall.service.msg.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.google.common.collect.Lists;
import com.sjd.mall.mapper.SjdMsgMapper;
import com.sjd.mall.service.msg.MsgService;
import com.sjd.wx.config.WxMaConfiguration;
import com.sjd.wx.config.WxMaProperties;
import com.sjd.wx.domain.SjdMember;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * MsgServiceImpl
 * <p>
 * API 订阅消息 {@literal https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html}
 *
 * @author seer
 * @version 1.0
 * @date 2022/1/19 11:15
 */
@Service
@Slf4j
public class MsgServiceImpl implements MsgService {

    @Autowired
    private SjdMsgMapper msgMapper;

    @Autowired
    private WxMaProperties properties;

    // TODO seer 2022/1/20 14:06 需要确定模板id，推送内容，推送场景
    private void sendDemo(SjdMember member, String v1, String v2) {
        String templateId = "1234";
        List<WxMaSubscribeMessage.MsgData> dataList = Lists.newArrayList(
                new WxMaSubscribeMessage.MsgData("keyword1", v1),
                new WxMaSubscribeMessage.MsgData("keyword1", v2));
        sendSubscribeMsg(member.getOpenId(), templateId, dataList);
    }


    /**
     * 发送到微信
     *
     * @return
     */
    private Object sendSubscribeMsg(String openid, String templateId, List<WxMaSubscribeMessage.MsgData> dataList) {
        WxMaService wxMaService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppId());
        try {
            wxMaService.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
                    .templateId(templateId).data(dataList).toUser(openid).build());
        } catch (WxErrorException e) {
            log.warn("微信订阅消息发送异常 ", e);
            return false;
        }
        return true;
    }

}